package com.itheima.service.impl;

import com.itheima.domain.SmsCode;
import com.itheima.service.SmsCodeService;
import com.itheima.utils.CodeUtils;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeoutException;

/**
 * ClassName: SmsCodeServiceImpl
 * Description:
 * Date: 2023/03/11 AM 12:32:36
 * <p>
 * project: springboot
 * package: com.itheima.service.impl
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
@Service
public class SmsCodeServiceImpl implements SmsCodeService {

    @Autowired
    private CodeUtils codeUtils;

    // /**
    //  * 发送验证码到手机
    //  *
    //  * @param tele {@link String}
    //  * @return {@link String}
    //  */
    // @Override
    // // @Cacheable(value = "smsCode",key = "#tele")
    // @CachePut(value = "smsCode", key = "#tele")
    // public String sendCodeToSms(String tele) {
    //     return codeUtils.generator(tele);
    // }
    //
    // /**
    //  * 检查验证码
    //  *
    //  * @param smsCode {@link String}
    //  * @return {@link Boolean}
    //  */
    // @Override
    // public boolean checkCode(SmsCode smsCode) {
    //     // 取出内存中的验证码与传递过来的验证码比对，如果相同，返回 true
    //     String code = smsCode.getCode();
    //     String cacheCode = codeUtils.get(smsCode.getTele());
    //     return cacheCode.equals(code);
    // }

    /**
     * 以下是 springboot 中使用 xmemcached
     */

    @Autowired
    private MemcachedClient memcachedClient;


    /**
     * 发送验证码到手机
     *
     * @param tele {@link String}
     * @return {@link String}
     */
    @Override
    public String sendCodeToSms(String tele) {
        String code = codeUtils.generator(tele);
        try {
            memcachedClient.set(tele, 10, code);
        } catch (TimeoutException | InterruptedException | MemcachedException e) {
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 检查验证码
     *
     * @param smsCode {@link String}
     * @return {@link Boolean}
     */
    @Override
    public boolean checkCode(SmsCode smsCode) {
        String code = null;
        try {
            code = memcachedClient.get(smsCode.getTele()).toString();
        } catch (TimeoutException | InterruptedException | MemcachedException e) {
            e.printStackTrace();
        }
        return smsCode.getCode().equals(code);
    }
}
